package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-data-hub/cache"
	"novel-data-hub/models"
	"strconv"
	"time"
)

func CarContractList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))
	offset := (page - 1) * size

	/*
			      SELECT
		  car_contracts.id AS ContractId,
		  car_cons.car_name AS CarName,
		  car_cons.car_type AS CarType,
		  car_cons.car_price AS CarPrice,
		  car_contracts.contract_code AS ContractCode,
		  car_contracts.contract_content AS ContractContent,
		  car_contracts.contract_status AS ContractStatus
		FROM
		  car_cons
		  LEFT JOIN car_contracts ON car_contracts.car_con_id = car_cons.id
		WHERE
		  car_contracts.id = 1
	*/
	var list []models.CarContractList
	redis_key := "car_contract_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("car_cons").
			Select("car_contracts.id AS ContractId",
				"car_cons.car_name AS CarName",
				"car_cons.car_type AS CarType",
				"car_cons.car_price AS CarPrice",
				"car_contracts.contract_code AS ContractCode",
				"car_contracts.contract_content AS ContractContent",
				"car_contracts.contract_status AS ContractStatus",
			).
			Joins("LEFT JOIN car_contracts ON car_contracts.car_con_id = car_cons.id").
			Offset(offset).
			Limit(size).
			Debug().
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	var count int64
	models.DB.Model(&models.CarContract{}).Count(&count)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  list,
		"count": count,
	})
	return
}

func CarContractDetail(c *gin.Context) {
	id := c.Query("id")

	var list models.CarContractList
	redis_key := "car_contract_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("car_cons").
			Select("car_contracts.id AS ContractId",
				"car_cons.car_name AS CarName",
				"car_cons.car_type AS CarType",
				"car_cons.car_price AS CarPrice",
				"car_contracts.contract_code AS ContractCode",
				"car_contracts.contract_content AS ContractContent",
				"car_contracts.contract_status AS ContractStatus",
			).
			Joins("LEFT JOIN car_contracts ON car_contracts.car_con_id = car_cons.id").
			Where("car_contracts.id = ?", id).
			Debug().
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": list,
	})
	return
}
